import axios from 'axios'
import URLparse from 'url-parse'

export class ApiRequest {
  _request = null;

  constructor(configs) {
    this._request = axios.create(configs);
    this._request.interceptors.response.use(function (response) {
      return response;
    }, function (error) {
      return Promise.reject(error);
    });
  }

  request() {
    return this._request;
  }

  async post(url, data = null, config = null) {
    return await this.request().post(url, data, config);
  }

  async get(url, config = null) {
    return await this.request().get(url, config);
  }

  async put(url, data = null, config = null) {
    return await this.request().put(url, data, config);
  }

  async delete(url, data = null, config = null) {
    return await this.request().delete(url, data, config);
  }

}

export default class Api {
  static _apiConfigs = {};

  static host(name) {
    let config = this.config(name);
    if (typeof config === 'function') {
      config = config.call(null);
    }
    return new ApiRequest(config);
  }

  static config(name, config = null) {
    if (config === null) {
      return this._apiConfigs[name];
    } else {
      this._apiConfigs[name] = config;
    }
  }

  static urlParse(url) {
    let urlParse = new URLparse(url);
    let apiRequest = null;
    if (urlParse.protocol === 'api:') {
      apiRequest = this.host(urlParse.host);
    } else {
      apiRequest = new ApiRequest({
        baseURL: urlParse.origin
      })
    }
    return {
      request: apiRequest,
      url: urlParse
    }
  }

  // static async post(url, data = null, config = null) {
  //   return await this.request().post(url, data, config);
  // }

  static async get(url, config = null) {
    let request = Api.urlParse(url);
    return await request.request.get(request.url.pathname, config);
  }

  static async post(url, data = null, config = null) {
    let request = Api.urlParse(url);
    return await request.request.post(request.url.pathname, data, config);
  }

  static async put(url, data = null, config = null) {
    let request = Api.urlParse(url);
    return await request.request.put(request.url.pathname, data, config);
  }


  //
  // static async put(url, data = null, config = null) {
  //   return await this.request().put(url, data, config);
  // }

  // static request(url) {
  //   let urlParse = new URLparse(url);
  //   if (urlParse.protocol === 'api:') {
  //
  //   }
  //   // let q2 = new URL(url);
  //   console.log(urlParse)
  // }


}
